package com.anysoft.register;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.anysoft.HostConstant;
import com.anysoft.MentorConst;
import com.anysoft.R;
import com.anysoft.base.BaseActivity;
import com.anysoft.bean.AccountLoginBean;
import com.anysoft.bean.BaseBean;
import com.anysoft.bean.UserBean;
import com.anysoft.event.RegisterEvent;
import com.anysoft.event.RegisterSuccessEvent;
import com.anysoft.linstener.OnNextLinstener;
import com.anysoft.login.SetFingerPrintActivity;
import com.anysoft.login.SetGestureStep1Activity;
import com.anysoft.me.callback.StringDialogCallback;
import com.anysoft.utils.ActivityUtils;
import com.anysoft.utils.AnalyticsEventUtils;
import com.anysoft.utils.CommonUtil;
import com.anysoft.utils.HttpUtils;
import com.anysoft.utils.MentorLogger;
import com.anysoft.utils.PreferencesUtils;
import com.anysoft.utils.RSACryptographyUtil;
import com.anysoft.utils.image.MD5Encoder;
import com.anysoft.view.dialog.DialogUtils;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by wwq on 2017/2/17.
 */

public class RegisterStep3Activity extends BaseActivity {


    @BindView(R.id.leftButton)
    Button leftButton;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.rightButton)
    Button rightButton;
    @BindView(R.id.titlebar)
    FrameLayout titlebar;
    @BindView(R.id.iv_register_step_1)
    ImageView ivRegisterStep1;
    @BindView(R.id.tv_register_step_1)
    TextView tvRegisterStep1;
    @BindView(R.id.iv_register_step_2)
    ImageView ivRegisterStep2;
    @BindView(R.id.tv_register_step_2)
    TextView tvRegisterStep2;
    @BindView(R.id.iv_register_step_3)
    ImageView ivRegisterStep3;
    @BindView(R.id.tv_register_step_3)
    TextView tvRegisterStep3;
    @BindView(R.id.tv_register_step_3_pwd_title)
    TextView tvRegisterStep3PwdTitle;
    @BindView(R.id.tv_register_step_3_pwd_level)
    TextView tvRegisterStep3PwdLevel;
    @BindView(R.id.iv_register_step_3_pwd)
    ImageView ivRegisterStep3Pwd;
    @BindView(R.id.ll_register_step_3_pwd)
    LinearLayout llRegisterStep3Pwd;
    @BindView(R.id.et_register_step_3_pwd)
    EditText etRegisterStep3Pwd;
    @BindView(R.id.tv_register_step_3_pwd_again)
    TextView tvRegisterStep3PwdAgain;
    @BindView(R.id.iv_register_step_3_pwd_again)
    ImageView ivRegisterStep3PwdAgain;
    @BindView(R.id.et_register_step_3_pwd_again)
    EditText etRegisterStep3PwdAgain;
    @BindView(R.id.btn_register_step_3)
    Button btnRegisterStep3;

    private RegisterEvent registerEvent;
    private String foucsOnPwd;

    /**
     * 密码是否校验合规
     */
    private boolean isPwdChekked = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_register_step_3);
        ButterKnife.bind(this);

        title.setText("开户");

        registerEvent = (RegisterEvent) getIntent().getSerializableExtra("registerEvent");

        etRegisterStep3Pwd.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    foucsOnPwd = etRegisterStep3Pwd.getText().toString();
                } else {
                    if (!foucsOnPwd.equals(etRegisterStep3Pwd.getText().toString())) {
                        checkPassword(false);
                    }
                }
            }
        });

        tvRegisterStep2.setTextColor(getResources().getColor(R.color.text_register_step_on));
        ivRegisterStep2.setBackgroundResource(R.mipmap.icon_sign_in_step2);
        tvRegisterStep3.setTextColor(getResources().getColor(R.color.text_register_step_on));
        ivRegisterStep3.setBackgroundResource(R.mipmap.icon_sign_in_step3);
        setOnNextLinstener(new OnNextLinstener() {
            @Override
            public void OnCancelNext() {

            }

            @Override
            public void OnConfirmNext() {
            }

            @Override
            public void OndoConfirm() {
                ActivityUtils.gotoRegisterStep1_1Activity(RegisterStep3Activity.this);
                finish();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * 校验密码是否合规
     */
    private void checkPassword(final boolean isFromButton) {
        Map<String, String> params = new HashMap<>();
        String password = etRegisterStep3Pwd.getText().toString();
        if (TextUtils.isEmpty(password)) {
            showConfirmAlert(mActivity, "请输入交易密码");
            return;
        }
        String rsaKey = getRsaKey();
        String rsaEncodePassword = "";
        if (!TextUtils.isEmpty(rsaKey)) {
            rsaEncodePassword = RSACryptographyUtil.encryptByPublicKey(password, rsaKey);
        }
        params.put("type", "0");//类型
        params.put("certificateNo", registerEvent.getIdentityNo());//证件号码
        params.put("password", rsaEncodePassword);//新密码
        OkGo.<String>post(HostConstant.CHECK_PASSWORD)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        MentorLogger.LogJson(TAG + "校验密码是否合规:", response.body());
                        parseJson_CheckPwd(response.body(), isFromButton);
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    /**
     * 解析校验密码是否合规接口返回的数据
     *
     * @param response
     */
    private void parseJson_CheckPwd(String response, boolean isFromButton) {
        BaseBean bean;
        try {
            bean = new Gson().fromJson(response, BaseBean.class);
        } catch (Exception exception) {
            showConfirmAlert(this, "提示", "数据解析错误");
            return;
        }

        if (!CommonUtil.checkState(this, bean, response)) {
            return;
        }

        isPwdChekked = true;
        if (isFromButton) {
            if (TextUtils.isEmpty(etRegisterStep3Pwd.getText().toString())) {
                showConfirmAlert(mActivity, "请输入交易密码");
                return;
            }
            if (etRegisterStep3Pwd.getText().toString().length() < 6 ||
                    etRegisterStep3Pwd.getText().toString().length() > 8) {
                showConfirmAlert(mActivity, "密码长度必须6至8位");
                return;
            }
            if (!isPwdChekked) {
                showConfirmAlert(mActivity, "请输入合规密码");
                return;
            }
            if (TextUtils.isEmpty(etRegisterStep3PwdAgain.getText().toString())) {
                showConfirmAlert(mActivity, "请再次输入交易密码");
                return;
            }
            if (!etRegisterStep3Pwd.getText().toString().equals(etRegisterStep3PwdAgain.getText().toString())) {
                showConfirmAlert(mActivity, "您两次输入的密码不一致，请重新输入");
                return;
            }
            AnalyticsEventUtils.toSetPasswordEvent(this);
            openAccount();
        }
    }

    private void openAccount() {
        String password = etRegisterStep3Pwd.getText().toString();
        String rsaKey = getRsaKey();
        String rsaEncodePassword = "";
        if (!TextUtils.isEmpty(rsaKey)) {
            rsaEncodePassword = RSACryptographyUtil.encryptByPublicKey(password, rsaKey);
        }
        Map<String, String> params = new HashMap<>();
        params.put("authApplyNo", registerEvent.getAuthApplyNo());
        params.put("bankCode", registerEvent.getBankCode());
        params.put("bankAccountNo", registerEvent.getBankAccountNo());
        params.put("trustChannelId", registerEvent.getTrustChannelId());
        params.put("username", registerEvent.getUsername());
        params.put("mobilePhone", registerEvent.getMobilePhone());
        params.put("identityType", registerEvent.getIdentityType());
        params.put("identityNo", registerEvent.getIdentityNo());
        params.put("provinceCode", registerEvent.getProvinceCode());
        params.put("cityCode", registerEvent.getCityCode());
        params.put("password", rsaEncodePassword);
        params.put("certificateValidEver", registerEvent.getCertificateValidEver());
        if ("1".equals(registerEvent.getCertificateValidEver())) {
            params.put("idValidDate", "");
        } else  if ("0".equals(registerEvent.getCertificateValidEver())) {
            params.put("idValidDate", registerEvent.getIdValidDate().replace("-", ""));
        }
        params.put("profession", registerEvent.getProfession());
        params.put("sex", registerEvent.getSex());
        params.put("birthday", registerEvent.getBirthday().replace("-", ""));
//        params.put("password", etRegisterStep3Pwd.getText().toString());
        params.put("recommendPerson", registerEvent.getRecommendPerson());
        //3.0.5新增
        params.put("address", registerEvent.getAddress());
        params.put("postCode", registerEvent.getPostCode());
        params.put("email", registerEvent.getEmail());
        //3.0.7新增 职务
        params.put("occupation", registerEvent.getOccupation());
        //3.0.7新增 账户控制人
        params.put("isExistActualControl", registerEvent.getIsExistActualControl());
        if ("1".equals(registerEvent.getIsExistActualControl())) {
            params.put("controllerName", registerEvent.getControllerName());
            params.put("controllerCertType", registerEvent.getControllerCertType());
            params.put("controllerCertNo", registerEvent.getControllerCertNo());
            params.put("controllerCertValidTerm", registerEvent.getControllerCertValidTerm());
            params.put("controllerInstruction", registerEvent.getControllerInstruction());
            params.put("controllerCertValidEver", registerEvent.getControllerCertValidEver());
        }
        //3.0.7新增 实际受益人
        params.put("actualBeneficiaryRelation", registerEvent.getActualBeneficiaryRelation());
        if ("1".equals(registerEvent.getActualBeneficiaryRelation())) {
            params.put("beneficiaryName", registerEvent.getBeneficiaryName());
            params.put("beneficiaryCertType", registerEvent.getBeneficiaryCertType());
            params.put("beneficiaryCertNo", registerEvent.getBeneficiaryCertNo());
            params.put("beneficiaryCertValidTerm", registerEvent.getBeneficiaryCertValidTerm());
            params.put("beneficiaryCertValidEver", registerEvent.getBeneficiaryCertValidEver());
            params.put("beneficiaryInstruction", registerEvent.getBeneficiaryInstruction());
        }
        //3.0.7新增不良记录
        params.put("hasBadCreditRecords", registerEvent.getHasBadCreditRecords());
        if ("1".equals(registerEvent.getHasBadCreditRecords())) {
            params.put("badCreditRecords", registerEvent.getBadCreditRecords());
        }
        //3.0.9改动个人涉税
        if (!"8".equals(registerEvent.getIdentityType()) && !"9".equals(registerEvent.getIdentityType()) && !"2".equals(registerEvent.getIdentityType())) {
            params.put("taxType", registerEvent.getTaxType());
            if (!"ON".equals(registerEvent.getTaxType())) {
                params.put("nameEn", registerEvent.getNameEn());
                params.put("surnameEn", registerEvent.getSurnameEn());
                params.put("domicileCountryCn", registerEvent.getDomicileCountry());
                params.put("domicileProvinceCn", registerEvent.getDomicileProvince());
                params.put("domicileCityCn", registerEvent.getDomicileCity());
                params.put("domicileLocationCn", registerEvent.getDomicileAddressCn());
                params.put("domicileLocationEn", registerEvent.getDomicileAddressEn());
                params.put("birthplaceCountryCn", registerEvent.getBirthplaceCountry());
                params.put("birthplaceProvinceCn", registerEvent.getBirthplaceProvince());
                params.put("birthplaceCityCn", registerEvent.getBirthplaceCity());
                params.put("taxTaxpayernoInfoRequest", new Gson().toJson(registerEvent.getTaxPayers()));
                MentorLogger.Loge(registerEvent.toString());
            }
        }
        String requestJson = new Gson().toJson(HttpUtils.getCommonParams(this, params));
        try {
            requestJson = MD5Encoder.encode(requestJson);
            requestJson = requestJson.toUpperCase();
            params.put("applicationNo", "" + requestJson);//
            MentorLogger.Loge(requestJson);
        } catch (Exception e) {
            e.printStackTrace();
        }
        OkGo.<String>post(HostConstant.OPEN_ACCOUNT)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        UpdateOpenAccount(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    private UserBean userBean;

    private void UpdateOpenAccount(String json) {
        hideLoading();
        AccountLoginBean bean;
        try {
            bean = new Gson().fromJson(json, AccountLoginBean.class);
        } catch (Exception exception) {
            showConfirmAlert(mActivity, "提示", "数据解析错误");
            return;
        }

        //3.0.8新增 开户信息校验 AC.CUSTOMER.CERTIFICATE.CHECK.FAIL=公安系统联网核查公民身份证件信息失败
        //                    AC.CUSTOMER.CERTIFICATE.CHECK.OVERTIMES=公安系统联网核查公民身份证件信息超过每日次数限制
        if (bean != null && "DSAC.CUSTOMER.CERTIFICATE.CHECK.FAIL".equals(bean.getRespCode())
                || "DSAC.CUSTOMER.CERTIFICATE.CHECK.OVERTIMES".equals(bean.getRespCode())) {
            showConfirmAlertWithLinstener(mActivity, "温馨提示", bean.getRespMsg(), "确定");
            return;
        }

        if (!CommonUtil.checkState(mActivity, bean, json)) {
            return;
        }

        if (bean == null || bean.getData() == null) {
            showConfirmAlert(mActivity, "提示", getString(R.string.no_data));
            return;
        }

        userBean = new UserBean();
        userBean.setUserName(bean.getData().getRealName());
        userBean.setUserId(bean.getData().getIdentityNo());
        userBean.setUserType(bean.getData().getIdentityType());
        userBean.setToken(bean.getData().getToken());
        userBean.setFundCustomerNo(bean.getData().getFundCustomerNo());
        userBean.setSex(bean.getData().getSex());
        userBean.setRecordIdentNumber("1");
        userBean.setLastLoginTime(System.currentTimeMillis());
        saveUser(userBean, bean);

        if (!registerEvent.getIdentityNo().equals(findUserId())) {
            clearSecretKey(mActivity);
        }
        PreferencesUtils.putString(this, MentorConst.LAST_LOGIN_USER_ID, bean.getData().getIdentityNo());

        AnalyticsEventUtils.toOpenAccountEvent(this);

        DialogUtils utils = new DialogUtils();
        utils.registerSuccess(mActivity, "恭喜您开户成功！");
        utils.setOnContentDialogSbtnListener(new DialogUtils.OnContentDialogSbtnListener() {
            @Override
            public void OnContentDialogSbtnClick() {

                check();
            }
        });
    }

    /**
     * 检查是否可以开启指纹或手势
     */
    private void check() {
        updateCheck();
    }

    private void updateCheck() {
        Intent intent;

        if (Double.parseDouble(minSdkVersion) >= 23 &&
                PreferencesUtils.getString(this, MentorConst.MOBILE_WHITE).contains(android.os.Build.MANUFACTURER)) {
            intent = new Intent().setClass(mActivity, SetFingerPrintActivity.class);
        } else {
            intent = new Intent().setClass(mActivity, SetGestureStep1Activity.class);
        }

        intent.putExtra(MentorConst.GET_PASSWORD, etRegisterStep3Pwd.getText().toString());
        intent.putExtra(MentorConst.GET_USERBEAN, userBean);
        startActivity(intent);
        EventBus.getDefault().post(new RegisterSuccessEvent(true));
        finish();
    }

    private boolean isShowPwd = false;

    @OnClick({R.id.leftButton, R.id.iv_register_step_3_pwd, R.id.btn_register_step_3})
    public void onClick(View view) {
        if (!isFastDoubleClick()) {
            switch (view.getId()) {
                case R.id.leftButton:
                    finish();
                    break;
                case R.id.iv_register_step_3_pwd:
                    String pwd = etRegisterStep3Pwd.getText().toString();
                    String pwdAgain = etRegisterStep3PwdAgain.getText().toString();
                    if (isShowPwd) {
                        etRegisterStep3Pwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                        etRegisterStep3PwdAgain.setTransformationMethod(PasswordTransformationMethod.getInstance());
                        isShowPwd = false;
                        ivRegisterStep3Pwd.setBackgroundResource(R.mipmap.icon_eye_close);
                    } else {
                        etRegisterStep3Pwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                        etRegisterStep3PwdAgain.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                        isShowPwd = true;
                        ivRegisterStep3Pwd.setBackgroundResource(R.mipmap.icon_eye);
                    }
                    etRegisterStep3Pwd.setSelection(pwd.length());
                    etRegisterStep3PwdAgain.setSelection(pwdAgain.length());
                    break;
                case R.id.btn_register_step_3:
                    checkPassword(true);
                    break;
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

}
